<?

class ImportController extends Controller{
    
    function actionIndex(){
        $this->actionImport();
    }
    
    function actionImport(){
        
        header('Content-type: text/html; charset=utf-8');
        
        $pop3 = new POP3($this->getModule()->import['host']);
        
        $pop3->pUSERPASS($this->getModule()->import['user'],$this->getModule()->import['password']);
        if($pop3->error){echo 'ERROR: '.$pop3->error; exit(0); }
        
        $messages = $pop3->pLIST();
        
        foreach($messages as $k=>$v){
            $params['include_bodies'] = true;
            $params['decode_bodies']  = false;
            $params['decode_headers'] = true;
            $params['input']          = $pop3->pRETR($k);
            $params['crlf']           = "\r\n";
            
            $structure = Mail_mimeDecode::decode($params);
            
            #echo debug($structure);
            
            $M = new MailInbox;
            $M->time_delivery = strtotime($structure->headers['delivery-date']);
            $M->headers = json_encode($structure->headers);
            
            if(isset($structure->parts)){
                foreach($structure->parts as $k=>$p){
                    if($p->headers['content-transfer-encoding'] == 'base64' && $p->ctype_secondary == 'plain'){
                        if(!empty($p->ctype_parameters['charset'])){
                            $M->charset = $p->ctype_parameters['charset'];
                        }
                        $M->body = $p->body;
                    }
                }
            }
            if($structure->body){
                $M->body = $structure->body;
                if(!empty($structure->ctype_parameters['charset'])){
                    $M->charset = $structure->ctype_parameters['charset'];
                }
            }
            
            $M->subject = 'no title';
            if(!empty($structure->headers['subject']))
                $M->subject = mb_convert_encoding($structure->headers['subject'], 'utf-8', $M->charset);
            
            $M->save();
            if($M->id > 0){
                $pop3->pDELE($k);
            }
            
            echo debug($M->attributes);
            
        }
        
        $pop3->pQUIT();
        
    }
    
}
